<template>
<!-- 优惠卷 -->
  <div id="Administration">
    <div id="managements">
      <!--搜索框 -->
      <div id="manage-top">
        <el-input placeholder="请输入优惠券标题" v-model="allPages.value"></el-input>
        <el-select v-model="allPages.type" clearable placeholder="请输入优惠券类型">
          <el-option
            style="height:46px"
            v-for="item in alltype"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select v-model="allPages.status" clearable placeholder="请输入优惠券状态">
          <el-option
            style="height:46px"
            v-for="item in dataState"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <button type="button" class="el-button el-button--primary" @click="management()">
          <i class="el-icon-search"></i>
          <span>查找</span>
        </button>
        <button type="button" class="el-button el-button--primary" @click="additions()" v-Promise="'promote:coupon:create'">
            <i class="el-icon-edit"></i><span>添加</span>
        </button>
        <button type="button" class="el-button el-button--primary" @click="exports()">
          <i class="el-icon-download"></i><span>当前页导出</span>
      </button>
      </div>
      <!-- 数据操作 -->
      <div id="manage-bottom">
        <el-table
          border
          :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          :key="id"
        >
          <el-table-column label="优惠卷ID" prop="id"></el-table-column>
          <el-table-column label="优惠券名称" prop="title"></el-table-column>
          <el-table-column label="优惠券类型" prop="type">
            <template slot-scope="scope">{{scope.row.type|types()}}</template>
          </el-table-column>
          <el-table-column label="介绍" prop="description"></el-table-column>
          <el-table-column label="优惠券数量" prop="total"></el-table-column>
          <el-table-column label="剩余数量" prop="surplus"></el-table-column>
          <el-table-column label="每个银领" prop="limit"></el-table-column>
          <el-table-column label="满减金额">
            <template slot-scope="scope">
              满减{{scope.row.discount}}元
            </template>
          </el-table-column>
          <el-table-column label="最低消费" prop="min">
            <template slot-scope="scope">
              满{{scope.row.min}}元可用
            </template>
          </el-table-column>
          <el-table-column label="状态" prop>
            <template slot-scope="scope">
              <el-tag>{{scope.row.status|scopes(scope.row.gmtEnd)}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="使用类目名称" prop="categoryTitle">
            <template slot-scope="scope">
              <el-tag>{{scope.row.categoryTitle|category()}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="使用类目ID" prop="categoryId"></el-table-column>
          <el-table-column label="领卷相对天数" prop="days">
            <template slot-scope="scope">
              {{scope.row.days|daysTitle()}}
            </template>
          </el-table-column>
          <el-table-column label="领卷开始时间" prop="gmtStart">
            <template slot-scope="scope">{{scope.row.gmtStart|formatDate()}}</template>
          </el-table-column>
          <el-table-column label="领卷结束时间" prop="gmtEnd">
            <template slot-scope="scope" prop="gmtCreate">{{scope.row.gmtEnd | formatDate()}}</template>
          </el-table-column>
          <el-table-column align="right" label="操作" width="250px;">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="statust(scope.$index,scope.row)"
                class="kohlrabiblue"
              >{{scope.row.status|statusreverse()}}</el-button>
              <el-button
                size="mini"
                @click="compile(scope.$index,scope.row)"
                class="kohlrabiblue"
                v-Promise="'promote:coupon:update'"
              >编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)" v-Promise="'promote:coupon:delete'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="block">
        <!-- current-change当前页size-change每页条数current-page当前页数，支持 .sync 修饰符page-sizes每页显示条目个数，支持 .sync 修饰符-->
        <Paging @handle="handles" :allPages="allPages"></Paging>
      </div>
      <div>
        <!-- 添加编辑弹框 -->
        <el-dialog :title="titleName" :visible.sync="dialogFormVisible">
          <div class="loginRight">
            <div class="login-right">
              <el-form
                :model="ruleForm"
                status-icon
                ref="ruleForm"
                :rules="rules"
                label-width="100px"
                class="demo-ruleForm">
                <!-- 优惠卷名称 -->
                <el-form-item prop="title" label="优惠卷名称">
                  <!-- <div class="login-img">优惠卷名称</div> -->
                  <el-input v-model.number="ruleForm.title"></el-input>
                </el-form-item>
                <!-- 优惠卷类型 -->
                <el-form-item label="优惠卷类型">
                  <el-select v-model="ruleForm.type">
                    <el-option
                      style="height:46px"
                      v-for="item in alltype"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- 介绍 -->
                <el-form-item prop="description" label="介绍">
                  <el-input v-model.number="ruleForm.description"></el-input>
                </el-form-item>
                <!-- 优惠卷数量 -->
                <el-form-item prop="total" label="优惠卷数量">
                  <el-input  v-model.number="ruleForm.total">
                      <template slot="append" >张</template>
                  </el-input>
                </el-form-item>
                <!-- 每个银领 -->
                <el-form-item prop="limit" label="每个银领">
                  <el-input  v-model.number="ruleForm.limit">
                      <template slot="append" >张</template>
                  </el-input>
                </el-form-item>
                <!-- 满减金额 -->
                <el-form-item prop="discount" label="满减金额">
                   <el-input  v-model.number="ruleForm.discount">
                      <template slot="append" >元</template>
                  </el-input>
                </el-form-item>
                <!-- 最低消费 -->
                <el-form-item prop="min" label="最低消费">
                   <el-input  v-model.number="ruleForm.min">
                      <template slot="append" >元</template>
                  </el-input>
                </el-form-item>
                <!-- 状态 -->
                <el-form-item label="状态">
                  <el-select v-model="ruleForm.status" placeholder="请选择推荐类型" >
                    <el-option
                      style="height:46px"
                      v-for="item in status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <!-- 有效期 -->
                <el-form-item label="有效期" id="deadline" >
                  <el-radio-group v-model="radio1" @change="conceal=!conceal" :disabled="forbidden">
                    <el-radio-button label="领券相对天数"></el-radio-button>
                    <el-radio-button label="指定绝对时间"></el-radio-button>
                  </el-radio-group>
                  <div>
                    <el-input v-model.number="ruleForm.days" v-show="conceal" :disabled="forbidden" style="margin-top: 17px;">
                      <template slot="append" >天</template>
                    </el-input>
                    <div class="time" v-show="!conceal" style="margin-top: 17px;">
                      <el-date-picker
                        v-model="ruleForm.gmtStart" value-format="timestamp"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      ></el-date-picker>
                    </div>
                  </div>
                </el-form-item>
                <!-- 商品限制范围 -->
                <div class="impose">
                  <el-form-item label="商品限制范围">
                    <el-radio-group v-model="radio2" @change="show=!show" :disabled="forbidden">
                      <el-radio-button label="全场通用"></el-radio-button>
                      <el-radio-button label="指定分类"></el-radio-button>
                    </el-radio-group>
                    <div class="poke" v-show="show">
                      <el-form-item label="推荐类型">
                        <el-cascader v-model="input" :options="spuTitl"></el-cascader>
                      </el-form-item>
                    </div>
                  </el-form-item>
                </div>
              </el-form>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="affirm()">
              <div>确 定</div>
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import coupon from "@/api/discount.js";
import Paging from "../../components/Paging"; //分页
import qs from "qs";
export default {
  components: {
    Paging
  },
  data() {
    //   优惠卷名称
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("优惠卷名称不能为空！"));
      } else {
        callback();
      }
    };
     //   优惠卷类型
    var totals = (rule, value, callback) => {
       let totalslabel=/^[0-9]{1,18}$/
      if (!value) {
        return callback(new Error("优惠卷类型不能为空！"));
      }
      if(!totalslabel.test(value)){
        return callback(new Error("优惠卷类型必须是数字整数！"));
      }else {
        callback();
      }
    }; 
     //   优惠卷数量
    var limits = (rule, value, callback) => {
      let limitslabel=/^[0-9]{1,18}$/
      if (!value) {
        return callback(new Error("优惠卷数量不能为空！"));
      }  
      if(!limitslabel.test(value)){
        return callback(new Error("优惠卷数量必须是数字整数！"));
      }else {
        callback();
      }
    }; 
     //   满减金额
    var discounts = (rule, value, callback) => {
      let discountslabel=/^[0-9]{1,18}$/
      if (!value) {
        return callback(new Error("满减金额不能为空！"));
      } 
      if(!discountslabel.test(value)){
        return callback(new Error("满减金额必须是数字整数！"));
      }else {
        callback();
      }
    };
     //   最低消费
    var mins = (rule, value, callback) => {
      let minlabel=/^[0-9]{1,18}$/
      if (!value) {
        return callback(new Error("最低消费不能为空！"));
      } 
      if(!minlabel.test(value)){
        return callback(new Error("最低消费必须是数字整数！"));
      }else {
        callback();
      }
    };
    return {
      forbidden:false,
      show:false,
      conceal: true,
      radio1: "领券相对天数",
      radio2: "全场通用",
      spuTitl: [],
      looktitle: "",
      alltype: [
        {
          value: 1,
          label: "满减卷"
        },
        {
          value: null,
          label: "全部"
        }
      ],
      status: [
        {
          value: 0,
          label: "下架"
        },
        {
          value: 1,
          label: "正常"
        },
        {
          value: null,
          label: "全部"
        }
      ],
      dataState: [
        {
          value: 0,
          label: "下架"
        },
        {
          value: 1,
          label: "正常"
        },
        {
          value: 2,
          label: "已过期"
        },
        {
          value: null,
          label: "全部"
        }
      ],
      state: [
        {
          value: "0",
          label: "冻结"
        },
        {
          value: "1",
          label: "激活"
        },
        {
          value: null,
          label: "全部"
        }
      ],
      id: "",
      input: "",
      search: "",
      titleName: "", //是否添加还是编辑
      tableData: [{}],
      dialogFormVisible: false, //弹窗口
      totalPageNo: 1,
      value1: [],
      allPages: {
        currentPage: 1, //当前的默认的页数
        eachpage: 10, //默认的页码
        total: 0, //初始值共数据条
        totalPageNo: 1,
        // 查询
        value: "",
        // 优惠券
        title: "",
        type: "",
        description: "",
        surplus: "",
        limit: "",
        discount: "",
        min: "",
        status: ""
      }, //分页
      ruleForm: {
        gender: "",
        alltype: "",
        title: "",
        type: "",
        description: "",
        total: "",
        surplus: "",
        limit: "",
        discount: "",
        min: "",
        status: "",
        categoryId: "",
        days: "",
        gmtStart: "",
        gmtEnd: "",
        id:""
      },
      rules: {
        title: [
          {
            validator: checkAge,
            trigger: "blur"
          }
        ],
        total:[
          {
            validator: totals,
            trigger: "blur"
          },
          { type:'number', message: '必须是数字类型', trigger: 'blur' }
        ],
        limit:[
          {
            validator: limits,
            trigger: "blur"
          },
          { type:'number', message: '必须是数字类型', trigger: 'blur' }
        ],
         discount:[
          {
            validator: discounts,
            trigger: "blur"
          },
          { type:'number', message: '必须是数字类型', trigger: 'blur' }
        ],
        min:[
          {
            validator: mins,
            trigger: "blur"
          },
          { type:'number', message: '必须是数字类型', trigger: 'blur' }
        ]
      }
    };
  },
  //时间戳
  filters: {
     formatDate: function(value) {
      let date = new Date(value);
      // let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      return value ?  MM + "-" + d + "- " + h + ":" + m + "" : "无";
    },
    types: function(value) {
      return value == 1 ? "满减卷" : "错误类型";
    },
    scopes: function(value,time) {
      return time<new Date().getTime()?"已过期":value == 0 ? "下架" : "正常";
    },
    statusreverse: function(value) {
      return value == 0 ? "激活" : "冻结";
    },
    category:function(value){
      return value ? value : "全部类目";
    },
    daysTitle:function(value){
      return value ? value : "无";
    }
  },
  methods: {
    // 导入导出
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    exports() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../vendor/Export2Excel");
        const tHeader = [
          "优惠卷ID","优惠券名称","优惠券类型","介绍","优惠券数量","剩余数量","每个限领","满减金额","最低消费","状态","使用类目名称","使用类目ID","领卷相对天数","领卷开始时间","领卷结束时间"];
        const filterVal = ["id","title","type","description","total","surplus","limit","discount","min","status","categoryTitle","categoryId","days","gmtStart","gmtEnd"
        ];
        const list = this.tableData;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "优惠券表格");
      });
    },
     // sup树
    supshu() {
        let _this=this;
      coupon.spuTitles().then(res => {
        console.log(res)
        _this.spuTitl =res.data.data
      });
    },
    // 编辑
    compile(index, row) {
      this.forbidden=true
      this.dialogFormVisible = true;
      this.titleName = "查看";
      this.modalType = "update";
      this.ruleForm = {...row}
    },
    //添加
    additions() {
       this.forbidden=false
      this.titleName = "创建";
      this.modalType = "add";
      this.dialogFormVisible = true;
      this.ruleForm={}
    },
    // 分页负值
    handles(val) {
      this.allPages = val;
      this.management();
    },
    // 管理员数据列表
    management() {
      let _this = this;
      coupon.discount(_this.allPages).then(function(res) {
        _this.tableData = res.data.data.items;
        _this.total = res.data.data.count;
        // 分页
        _this.allPages.currentPage = res.data.data.pageNo;
        _this.allPages.eachpage = res.data.data.pageSize;
        _this.allPages.total = res.data.data.total;
        _this.allPages.totalPageNo = res.data.data.totalPageNo;
      });
    },
    // 删除
    handleDelete(index, row) {
      var _this = this;
      // 提示框
      _this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          _this.$information.success('删除成功')
          let data = {
            id: _this.tableData[index].id
          };
          coupon.handleDeletec(data).then(function(res) {
            _this.tableData.splice(index, 1);
          });
        });
    },
    statust(index, row) {
      let _this = this;
      coupon.status(row).then(function(res) {
         _this.$information.success('这是一条状态操作成功的提示消息')
        // 判断是否冻结还是激活
        if (row.status === 1) {
          row.status = 0;
        } else {
          row.status = 1;
        }
        for (const i in _this.tableData) {
          if (_this.tableData[i].id === row.id) {
            _this.tableData[i].status = row.status;
          }
        }
      });
    },
    // 判断是否添加还是编辑
    affirm() {
      let _this = this;
      //添加
         if (_this.titleName === "创建") {
           if(_this.ruleForm.discount==_this.ruleForm.min){
                    coupon.addition(_this.ruleForm).then(function(res) {
          if (res.data.errmsg == "成功") {
            _this.$information.success('这是一条添加成功的提示消息')
            _this.dialogFormVisible = false;
            _this.management()
          } else {
             _this.$information.error('这是一条添加失败的提示消息') 
          }
        });    
           }else{
        _this.$information.error('满减金额不能超过最低消费！')
           }
      }
    
       // 编辑
      if (_this.titleName === "查看") {
        coupon.compile(_this.ruleForm).then(function(res) {
            if (res.data.errmsg == "成功") {
                 _this.$information.success('这是一条编辑成功的提示消息')
                  _this.dialogFormVisible = false;
                _this.management()
            }else{
                _this.$information.error('这是一条编辑失败的提示消息')
            }
        });
      }
     
    }
  },
  created() {
    this.management();
    this.supshu(); //sup树
  },
   watch:{
    dialogFormVisible(){
      this.$nextTick(() => {
       this.$refs.ruleForm.clearValidate();
      })
    }
  }
};
</script>

<style scoped>
#Administration {
  width: 100%;
  height: 100%;
}
#Administration ::-webkit-scrollbar {
  width: 0px !important;
}
#managements {
  width: 80vw;
  height: 80vh;
  margin: auto;
}
/* 搜索框 */
#manage-top {
  width: 100vw;
  display: flex;
  margin-bottom: 30px;
}
#manage-top .el-input__inner {
  width: 200px;
}
.el-input {
  width: 210px;
}

/* 表格样式*/
#block {
  margin-top: 30px;
}
.kohlrabiblue {
  background: #66b1ff;
  color: #ffffff;
}
.el-table--enable-row-transition/deep/.el-table__body td {
  text-align: center;
}
.el-table/deep/th.is-sortable {
  cursor: pointer;
  text-align: center;
}
.el-table td,
.el-table/deep/th.is-leaf {
  text-align: center;
}
/*  */
.loginRight {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 0px 8px 8px 0px;
}
.login-right {
  width: 80%;
  margin: auto;
}
.loginRight .login-title {
  color: #333;
  margin-bottom: 40px;
  font-weight: 500;
  font-size: 22px;
  text-align: center;
  letter-spacing: 4px;
  margin-top: 40px;
}
.el-form-item/deep/input {
  background: transparent;
  border-radius: 0;
  color: #333;
  display: inline;
}
.el-form-item {
  height: 50px !important;
  position: relative;
}
.el-form-item/deep/i {
  display: inline;
}
.impose {
  padding-top: 40px;
  position: relative;
}
.poke {
  position: absolute;
  top: 55px;
  left: -102px;
}
.el-checkbox {
  width: 300px;
  margin: 20px 0px 30px 0px;
}
/* 弹出框 */
.el-input-group__append {
  position: relative;
  top: -40px;
  left: 210px;
}
#deadline {
  position: relative;
}
.time {
  position: absolute;
  top: 42px;
  left: 0px;
}
.el-form-item__content {
    height: 10px;
}

</style>